package com.mini.config;

import com.mini.service.MiniAdminService;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author zl
 * @version 1.0
 * @date Created in 2020/2/28
 */

@Component
@Slf4j
public class CheckloginInterceptor extends HandlerInterceptorAdapter {

    @Value("${devMode}")
    private Boolean devMode;

    @Autowired
    private MiniAdminService mnsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(devMode){
            return true;
        }

        CheckLogin annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(CheckLogin.class);
        }else{
            return true;
        }

        if(Objects.isNull(annotation)){
            return true;
        }

        String token = request.getHeader("Authorization");
        if(StringUtils.isBlank(token)){
            throw new UnLoginException("unauthorized");
        }

        UserVO userVO = mnsService.getLoginUser(token);
        if(Objects.nonNull(userVO)){
            request.setAttribute("_LOGIN_USER_INFO",userVO);
            return true;
        }else{
            throw new UnLoginException("token expired");
        }

    }









}
